import Router from 'koa-router'
import Redis from 'kos-redis'
import nodeMailer from 'nodemailer'
import User from './utils/passport'
import axios from './utils/axios'
import Email from '../meituan/config'
import {
  async
} from 'q'
import passport from './utils/passport'

let router = new Router({
  prefix: 'users'
})

let Store = new Redis().client

// 注册
router.post('/signup', async (ctx) => {
  const {
    username,
    password,
    email,
    code
  } = ctx.request.body

  if (code) {
    const saveCode = await Store.hget(`nodemail:${username}`, 'code')
    const saveExpire = await Store.hget(`nodemail:${username}`, 'expire')
    if (code === saveCode) {
      if (new Date().getTime() - saveExpire > 0) {
        ctx.body = {
          code: 0,
          msg: '验证码已过期，请重新获取验证码'
        }
        return false
      }
    } else {
      ctx.body = {
        code: 0,
        msg: '验证码错误，请重试'
      }
    }
  } else {
    ctx.body = {
      code: 0,
      msg: '请填写验证码'
    }
  }
  let user = await User.find({
    username
  })
  if (user.length) {
    ctx.body = {
      code: 0,
      msg: '用户名已被注册'
    }
    return
  }
  let nuser = await User.create({
    username,
    password,
    email
  })
  if (nuser) {
    let res = await axios.post('/users/signin', {
      username,
      password,
    })
    if(res.data && res.data.code === 1){
      ctx.body = {
        code:1,
        msg:'注册成功',
        user:res.data.user
      }
    }else{
      ctx.body = {
        code:0,
        msg:'注册失败',
        user:res.data.user
      }
      return
    }
  }else{
    ctx.body = {
      code:0,
      msg:'注册失败',
      user:res.data.user
    }
    return
  }
})

// 登录
router.post('/signin', async (ctx) =>{
  return passport.authenticate('local',function(err,user,info,status){
    if(err){
      ctx.body = {
        code:0,
        msgL:err
      }
    }
  })
})
